﻿#region Usings

using System;
using System.Collections.Generic;
using FluentValidation;
using FluentValidation.Results;
using FluentValidation.Validators;

#endregion

namespace Yandex.Market.Api.Validation
{
    internal class CollectionValidator<TBase> : ChildCollectionValidatorAdaptor where TBase : class
    {
        public CollectionValidator(PolymorphicChildValidator<TBase> validator) : base(validator)
        {}
    }

    internal class PolymorphicChildValidator<TBase> : AbstractValidator<TBase> where TBase : class
    {
        private readonly Dictionary<Type, IValidator> _validatorMappings = new Dictionary<Type, IValidator>();

        public PolymorphicChildValidator<TBase> Add<TChild>(IValidator<TChild> validator) where TChild : TBase
        {
            _validatorMappings[typeof(TChild)] = validator;

            return this;
        }

        public override ValidationResult Validate(ValidationContext<TBase> context)
        {
            var instanceToValidate = context.InstanceToValidate;

            IValidator actualValidator = null;

            if(instanceToValidate != null)
                _validatorMappings.TryGetValue(instanceToValidate.GetType(), out actualValidator);

            var ctx = new ValidationContext(instanceToValidate, context.PropertyChain, context.Selector);

            return actualValidator != null ? actualValidator.Validate(ctx) : new ValidationResult();
        }
    }
}